package com.spx.core.ui.properties;

import java.util.Set;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.dialogs.PropertyPage;

import com.spx.core.CoreActivator;
import com.spx.core.types.Role;
import com.spx.core.types.User;
import com.spx.kernel.ui.widgets.DoubleListSelector;

public class UserRolePropertyPage extends PropertyPage
{


	
	
	String id;

	User user;
	Set<Role> chosenRoles;

	Set<Role> allRoles;

	private DoubleListSelector<Role> selector;

	/**
	 * Constructor for SamplePropertyPage.
	 */
	public UserRolePropertyPage()
	{
		super();
	}

	private void addFirstSection(Composite composite)
	{

		final IAdaptable userAdaptor = getElement();
		user = (User) userAdaptor.getAdapter(User.class);
		id = user.getId();

		chosenRoles = user.getRoles();
		allRoles = CoreActivator.getDefault().getSecurityService().fetchAllRoles(0, Integer.MAX_VALUE);

	
		final GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.horizontalSpan = 3;
	

		selector = new DoubleListSelector<Role>(composite, SWT.NONE, allRoles, chosenRoles);
		selector.setLayoutData(gridData2);
	}

	/**
	 * @see PreferencePage#createContents(Composite)
	 */
	@Override
	protected Control createContents(Composite parent)
	{
		final Composite composite = createDefaultComposite(parent);
		addFirstSection(composite);

		return composite;
	}

	private Composite createDefaultComposite(Composite parent)
	{

		final Composite composite = new Composite(parent, SWT.NONE);
		final GridLayout layout = new GridLayout(2, true);
		composite.setLayout(layout);
		final GridData data = new GridData(GridData.FILL);
		data.grabExcessHorizontalSpace = true;
		composite.setLayoutData(data);

		return composite;
	}

	@Override
	protected void performDefaults()
	{

	}

	@Override
	public boolean performOk()
	{
		user.getRoles().addAll(selector.getChosen());
		CoreActivator.getDefault().getSecurityService().modify(user);
		// store the value in the owner text field
		return true;
	}

	@Override
	protected void performApply()
	{
		user.getRoles().addAll(selector.getChosen());
		super.performApply();
	}
	
	
	
}